﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.Office.Interop.Excel;

namespace ObjectModel.Excel
{
    public static class ApplicationExtensions
    {
        /// <summary>
        /// Returns a Workbook object given the full name and short name of the workbook,
        /// opening the workbook if it's not already open.
        /// </summary>
        /// <param name="app"></param>
        /// <param name="name"></param>
        /// <param name="fullName"></param>
        /// <returns></returns>
        public static Workbook GetWorkbookFromNames(this Application app, string name, string fullName, out bool wbOpenedProgrammatically)
        {
            Workbook wb = null;
            wbOpenedProgrammatically = false;

            // First assume the workbook is open and try and find it in the current app.
            try { wb = app.Workbooks[name]; }
            catch (COMException)
            {
                // Look for the workbook in the file system and open in the current app.
                if (File.Exists(fullName))
                {
                    try
                    {
                        wb = app.Workbooks.Open(fullName, System.Type.Missing, true); // Open workbook as read-only
                        wbOpenedProgrammatically = true;
                    }
                    catch (COMException) { throw new InvalidOperationException(fullName + " cannot be opened."); }
                }
                else
                    throw new InvalidOperationException(fullName + " does not exist.");
            }

            return wb;
        }

        /// <summary>
        /// Returns a Range object from a the current application. Returns null if the range
        /// object is inaccessible (e.g. due to it's parent workbook not being open).
        /// </summary>
        /// <param name="app"></param>
        /// <param name="extAddress"></param>
        /// <returns></returns>
        public static Range GetRangeFromExternalAddress(this Application app, string extAddress)
        {

            Range range = null;

            try { range = app.Range[extAddress]; }
            catch (System.Runtime.InteropServices.COMException) { }

            return range;
        }
    }
}
